package com.sjgtw.cloud.web.repairRecords.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.sjgtw.cloud.common.core.constant.CacheConstants;
import com.sjgtw.cloud.common.core.utils.DateUtils;
import com.sjgtw.cloud.common.core.utils.SecurityUtils;
import com.sjgtw.cloud.common.core.utils.StringUtils;
import com.sjgtw.cloud.common.core.web.domain.AjaxResult;
import com.sjgtw.cloud.common.redis.service.RedisService;
import com.sjgtw.cloud.service.SystemServerService;
import com.sjgtw.cloud.system.api.model.LoginUser;
import com.sjgtw.cloud.web.repairRecords.domain.RepairRecords;
import com.sjgtw.cloud.web.repairRecords.mapper.RepairRecordsMapper;
import com.sjgtw.cloud.web.repairRecords.service.IRepairRecordsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 圬工补修记录Service业务层处理
 * 
 * @author lvyoufang
 * @date 2024-03-14
 */
@Service
public class RepairRecordsServiceImpl implements IRepairRecordsService 
{
    @Autowired
    private RepairRecordsMapper repairRecordsMapper;

    @Autowired
    private SystemServerService systemServerService;

    @Autowired
    private RedisService redisService;

    /**
     * 查询圬工补修记录
     * 
     * @param id 圬工补修记录主键
     * @return 圬工补修记录
     */
    @Override
    public RepairRecords selectRepairRecordsById(Long id)
    {
        return repairRecordsMapper.selectRepairRecordsById(id);
    }

    /**
     * 查询圬工补修记录列表
     * 
     * @param repairRecords 圬工补修记录
     * @return 圬工补修记录
     */
    @Override
    public List<RepairRecords> selectRepairRecordsList(RepairRecords repairRecords)
    {
        return repairRecordsMapper.selectRepairRecordsList(repairRecords);
    }

    /**
     * 新增圬工补修记录
     * 
     * @param repairRecords 圬工补修记录
     * @return 结果
     */
    @Override
    public int insertRepairRecords(RepairRecords repairRecords)
    {
        String token = SecurityUtils.getToken();
        String userKey = CacheConstants.LOGIN_TOKEN_KEY + token;
        LoginUser user = redisService.getCacheObject(userKey);

        repairRecords.setCreateUserId(user.getUserid());
        repairRecords.setCreateBy(user.getUsername());
        repairRecords.setCreateTime(DateUtils.getNowDate());
        return repairRecordsMapper.insertRepairRecords(repairRecords);
    }

    /**
     * 修改圬工补修记录
     * 
     * @param repairRecords 圬工补修记录
     * @return 结果
     */
    @Override
    public int updateRepairRecords(RepairRecords repairRecords)
    {
        String token = SecurityUtils.getToken();
        String userKey = CacheConstants.LOGIN_TOKEN_KEY + token;
        LoginUser user = redisService.getCacheObject(userKey);

        repairRecords.setUpdateBy(user.getUsername());
        repairRecords.setUpdateTime(DateUtils.getNowDate());
        return repairRecordsMapper.updateRepairRecords(repairRecords);
    }

    /**
     * 批量删除圬工补修记录
     * 
     * @param ids 需要删除的圬工补修记录主键
     * @return 结果
     */
    @Override
    public int deleteRepairRecordsByIds(String[] ids)
    {
        return repairRecordsMapper.deleteRepairRecordsByIds(ids);
    }

    /**
     * 删除圬工补修记录信息
     * 
     * @param id 圬工补修记录主键
     * @return 结果
     */
    @Override
    public int deleteRepairRecordsById(Long id)
    {
        return repairRecordsMapper.deleteRepairRecordsById(id);
    }

    @Override
    public List<String> check(List<RepairRecords> entities) {
        List<String> errors = new ArrayList<>();
        String token = SecurityUtils.getToken();
        String userKey = CacheConstants.LOGIN_TOKEN_KEY + token;
        LoginUser user = redisService.getCacheObject(userKey);

        List<String> deptNames = extractAndDeduplicateNames(entities);
        AjaxResult result = systemServerService.getDeptByNames(StringUtils.join(deptNames, ","));
        Map<String, Long> deptMap = new HashMap<>();
        if (result != null) {
            Object object = result.get("data");
            if (object != null) {
                JSONArray jsonArray = JSONArray.parseArray(JSONArray.toJSONString(object));
                if (!jsonArray.isEmpty()) {
                    for (int i=0; i<jsonArray.size();i++) {
                        JSONObject json = jsonArray.getJSONObject(i);
                        deptMap.put(json.getString("deptName"), json.getLong("deptId"));
                    }
                }
            }
        }

        for (RepairRecords entity : entities) {
            if (StringUtils.isEmpty(entity.getSectionName())) {
                errors.add("序号为" + entity.getNum() + "行数据区段不能为空");
            } else if (deptMap.containsKey(entity.getSectionName())) {
                entity.setSection(deptMap.get(entity.getSectionName()));
            } else {
                errors.add("序号为" + entity.getNum() + "行数据区段不存在");
            }

            if (StringUtils.isEmpty(entity.getWorkAreaName())) {
                errors.add("序号为" + entity.getNum() + "行数据工区不能为空");
            } else if (deptMap.containsKey(entity.getWorkAreaName())) {
                entity.setWorkArea(deptMap.get(entity.getWorkAreaName()));
            } else {
                errors.add("序号为" + entity.getNum() + "行数据工区不存在");
            }
            if (user != null) {
                entity.setCreateUserId(user.getUserid());
                entity.setCreateBy(user.getUsername());
            }
            entity.setCreateTime(DateUtils.getNowDate());
        }
        return errors;
    }

    @Override
    public void batchSave(List<RepairRecords> entities) {
        if (entities != null && entities.size() > 0) {
            if (entities.size() >= 200) {
                int index = 0;
                while (index <= entities.size()) {
                    int last = Math.min(index + 200, entities.size());
                    List<RepairRecords> temp = entities.subList(index, last );
                    if (temp != null && temp.size() > 0) {
                        repairRecordsMapper.batchSave(temp);
                    }
                    index += 200;
                }
            } else {
                repairRecordsMapper.batchSave(entities);
            }
        }
    }


    private static List<String> extractAndDeduplicateNames(List<RepairRecords> entities) {
        Set<String> uniqueNamesSet = new HashSet<>();

        for (RepairRecords entity : entities) {
            uniqueNamesSet.add(entity.getSectionName());
            uniqueNamesSet.add(entity.getWorkAreaName());
        }

        return new ArrayList<>(uniqueNamesSet);
    }
}
